<?php
function mobile_service_soil_info_list($parameters)
{

    global $user;
    $user_info = _get_user_info($user->uid);
    $query = db_select('soil_info', 'I');
    $query->leftjoin('farmer', 'F', 'F.farmer_id=I.farmer_id');
    $query->fields('I');
    $query->addField('F', 'farmer_name');
    $query->addField('F', 'addr_id');
    $query->join('addr', 'A', 'A.addr_id=F.addr_id');
    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    $query->leftJoin('addr', 'A4', 'A.town_id=A4.addr_id');
    $query->leftJoin('addr', 'A5', 'A.village_id=A5.addr_id');


    $query->leftJoin('plant', 'PP', 'PP.plant_id=I.pre_plant_id');
    $query->leftJoin('plant', 'PR', 'PR.plant_id=I.rec_plant_id');

    if ($user_info['role'] === '农户') {
        $datestr = '';
        if (!empty($form_state['values']['year'])) {//查询条件
            if ($form_state['values']['year']) {
                $datestr .= $form_state['values']['year'] . '-';
            }
        }
        if ($datestr) {
            $query->condition('I.sample_date', db_like($datestr) . '%', 'LIKE');
        }
        $query->condition('I.farmer_id', $user->uid);
    } else {
        if(!user_access('view all soil_info') && user_access('view own soil_info')){
            $query->condition('I.author_uid',$user->uid, '=');
        }
        if (!empty($form_state['values']['village'])) {//村落级
            $query->condition('A.village_id', $form_state['values']['village'], '=');
        } else if (!empty($form_state['values']['town'])) {//乡镇级
            $query->condition('A.town_id', $form_state['values']['town'], '=');
        } else if (!empty($form_state['values']['county'])) {//县级
            $query->condition('A.county_id', $form_state['values']['county'], '=');
        } elseif (!empty($form_state['values']['city'])) {//市级
            $query->condition('A.city_id', $form_state['values']['city'], '=');
        } elseif (!empty($form_state['values']['province'])) {//省级
            $query->condition('A.province_id', $form_state['values']['province'], '=');
        }
        if (!empty($form_state['values']['farmer'])) {
            $query->condition('I.farmer_id', $form_state['values']['farmer']);
        }
        if (!empty($form_state['values']['sampler'])) {
            $query->condition('I.sampler', '%' . db_like($form_state['values']['sampler']) . '%', 'LIKE');
        }
        if (!empty($_GET['farmer_id'])) {
            $query->condition('I.farmer_id', $_GET['farmer_id']);
            $form_state['farmer'] = $_GET['farmer_id'];
        }
        if (!empty($form_state['farmer'])) {//
            $query->condition('I.farmer_id', $form_state['farmer'], '=');
        }
        if (!empty($form_state['addr_id'])) {//
            $query->condition('F.addr_id', $form_state['addr_id'], '=');
        }
        if (!empty($form_state['values']['farmer_id'])) {//
            $query->condition('I.farmer_id', $form_state['values']['farmer_id'], '=');
        }
    }
    if (!empty($form_state['values']['field'])) {
        if (!empty($form_state['values']['min_number']) && !empty($form_state['values']['max_number'])) {
            $db_and = db_and();
            $db_and->condition('I.' . $form_state['values']['field'], $form_state['values']['min_number'], '>');
            $db_and->condition('I.' . $form_state['values']['field'], $form_state['values']['max_number'], '<');
            $query->condition($db_and);
        } elseif (!empty($form_state['values']['min_number'])) {
            $query->condition('I.' . $form_state['values']['field'], $form_state['values']['min_number'], '>');
        } elseif (!empty($form_state['values']['max_number'])) {
            $query->condition('I.' . $form_state['values']['field'], $form_state['values']['max_number'], '<');
        }
    }
    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');
    $query->addField('A4', 'name', 'town');
    $query->addField('A5', 'name', 'village');
    $query->addField('F', 'farmer_id');
    $query->addField('PP', 'plant_name','pre_plant_name');
    $query->addField('PR', 'plant_name','rec_plant_name');
    $query->orderBy('I.soil_info_id', 'DESC');
    if (!empty($parameters['cursor']) && !empty($parameters['comparator'])) { //游标翻页
        $query->condition('I.soil_info_id', $parameters['cursor'], $parameters['comparator']);
    }
    $query->range(0,10);

    $results = $query->execute();
    $results_list = [];
    if(!empty($results)){
        foreach ($results as $result) {
            $results_list[] = $result;
        }
    }
    return  ["data"=>$results_list];
}
function soil_info_add_validate( &$parameters) {
    $validata_error = '';
   
    return $validata_error;
}

function mobile_service_soil_info_add($parameters)
{
    global $user;
    $module_name="soil_info";
    $id = $parameters['soil_info_id'];
    $transaction = db_transaction();
    try {
        if (empty($id)) {
            if(!user_access('add '.$module_name)){
                return ['option'=>0,'errorNum'=>3];
            }
            $nid = db_insert('soil_info')
                ->fields(array(
                    'farmer_id' => $parameters['farmer_id'],
                    'title' => $parameters['title'],
                    'location' => $parameters['location'],
                    'sampler' => $parameters['sampler'],
                    'pre_plant_id' => $parameters['pre_plant_id'],
                    'rec_plant_id' => $parameters['rec_plant_id'],
                    'sample_date' => $parameters['sample_date'],
                    'target_yield' => _empty_2_zero($parameters['target_yield']),
                    'nitrogen' => _empty_2_zero($parameters['nitrogen']),
                    'phosphorus' => _empty_2_zero($parameters['phosphorus']),
                    'potassium' => _empty_2_zero($parameters['potassium']),
                    'organicmatter' => _empty_2_zero($parameters['organicmatter']),
                    'ph' => _empty_2_zero($parameters['ph']),
                    'calcium' => _empty_2_zero($parameters['calcium']),
                    'magnesium' => _empty_2_zero($parameters['magnesium']),
                    'sulfur' => _empty_2_zero($parameters['sulfur']),
                    'zinc' => _empty_2_zero($parameters['zinc']),
                    'copper' => _empty_2_zero($parameters['copper']),
                    'iron' => _empty_2_zero($parameters['iron']),
                    'boron' => _empty_2_zero($parameters['boron']),
                    'manganese' => _empty_2_zero($parameters['manganese']),
                    'author_uid' => $user->uid,
                    'timestamp' => time(),
                ))
                ->execute();
            for ($i = 0; $i < count($parameters['subfertilizer']); $i++) {
                $fertilizer = $parameters['subfertilizer'][$i];
                $fid = db_insert('fertilizer_recommendation')
                    ->fields(array(
                        'soil_info_id' => $nid,
                        'type' => $fertilizer['type'],
                        'fertilizer_id' => $fertilizer['fertilizer_id'],
                        'fertilization_date' => $fertilizer['fertilization_date'],
                        'fertilization_method' => $fertilizer['fertilization_method'],
                        'fertilizer_quantity' => _empty_2_zero($fertilizer['fertilizer_quantity']),
//                        'comments' => $fertilizer['comments'],
                        'author_uid' => $user->uid,
                        'timestamp' => time(),
                    ))
                    ->execute();
            }
            $result_option = (object)["option" => 1];
            return $result_option;
        } else {
            if(!mobile_user_edit_access($module_name,$module_name.'_id',$id,'edit own '.$module_name,'edit all '.$module_name)){
                return ['option'=>0,'errorNum'=>3];
            }
            $nid = db_update('soil_info')
                ->fields(array(
                    'farmer_id' => $parameters['farmer_id'],
                    'title' => $parameters['title'],
                    'location' => $parameters['location'],
                    'sampler' => $parameters['sampler'],
                    'pre_plant_id' => $parameters['pre_plant_id'],
                    'rec_plant_id' => $parameters['rec_plant_id'],
                    'sample_date' => $parameters['sample_date'],
                    'target_yield' => _empty_2_zero($parameters['target_yield']),
                    'nitrogen' => _empty_2_zero($parameters['nitrogen']),
                    'phosphorus' => _empty_2_zero($parameters['phosphorus']),
                    'potassium' => _empty_2_zero($parameters['potassium']),
                    'organicmatter' => _empty_2_zero($parameters['organicmatter']),
                    'ph' => _empty_2_zero($parameters['ph']),
                    'calcium' => _empty_2_zero($parameters['calcium']),
                    'magnesium' => _empty_2_zero($parameters['magnesium']),
                    'sulfur' => _empty_2_zero($parameters['sulfur']),
                    'zinc' => _empty_2_zero($parameters['zinc']),
                    'copper' => _empty_2_zero($parameters['copper']),
                    'iron' => _empty_2_zero($parameters['iron']),
                    'boron' => _empty_2_zero($parameters['boron']),
                    'manganese' => _empty_2_zero($parameters['manganese']),
                ))
                ->condition('soil_info_id', $id, '=')
                ->execute();
            for ($i = 0; $i < count($parameters['subfertilizer']); $i++) {
                $fertilizer = $parameters['subfertilizer'][$i];
                if (isset($fertilizer['id']) && !empty($fertilizer['id'])) {
                    continue;
                }
                $fid = db_insert('fertilizer_recommendation')
                    ->fields(array(
                        'soil_info_id' => $id,
                        'type' => $fertilizer['type'],
                        'fertilizer_id' => $fertilizer['fertilizer_id'],
                        'fertilization_date' => $fertilizer['fertilization_date'],
                        'fertilization_method' => $fertilizer['fertilization_method'],
                        'fertilizer_quantity' => _empty_2_zero($fertilizer['fertilizer_quantity']),
//                        'comments' => $fertilizer['comments'],
                        'author_uid' => $user->uid,
                        'timestamp' => time(),
                    ))
                    ->execute();
            }
            $result_option = (object)["option" => 1];
            return $result_option;
        }
    } catch (Exception $e) {
        $transaction->rollback();
        $result_option = (object)["option" => 0,"error"=>$e->getMessage()];
        return $result_option;
    }
}
